package cn.liip.demo.controller;

import java.io.IOException;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.liip.demo.websocket.WebSocketServer;

/**
 * WebSocket服务器端推送消息示例Controller
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/websocket")
public class WebSocketController {
	// 页面请求
	@GetMapping("/index")
	public ModelAndView index() {
		ModelAndView view = new ModelAndView("/index");
		return view;
	}

	// 页面请求
	@GetMapping("/socket/{cid}")
	public ModelAndView socket(@PathVariable String cid) {
		ModelAndView view = new ModelAndView("/websocketTest");
		// 设置跳转的视图 默认映射到 src/main/resources/templates/{viewName}.html
		// view.setViewName("websocket");
		view.addObject("cid", cid);
		return view;
	}

	// 推送数据接口
	@RequestMapping("/socket/push/{cid}")
	public String pushToWeb(@PathVariable String cid, String message) {
		try {
			WebSocketServer.SendMessage(cid, message);
		} catch (IOException e) {
			e.printStackTrace();
			return cid + "#" + e.getMessage();
		}
		return cid;
	}

	/**
	 * 群发消息内容
	 * 
	 * @param message
	 * @return
	 */
	@RequestMapping(value = "/sendAll", method = RequestMethod.GET)
	public String sendAllMessage(@RequestParam(required = true) String message) {
		try {
			WebSocketServer.BroadCastInfo(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "ok";
	}

	/**
	 * 指定会话ID发消息
	 * 
	 * @param message 消息内容
	 * @param id      连接会话ID
	 * @return
	 */
	@RequestMapping(value = "/sendOne", method = RequestMethod.GET)
	public String sendOneMessage(@RequestParam(required = true) String message,
			@RequestParam(required = true) String id) {
		try {
			WebSocketServer.SendMessage(id, message);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "ok";
	}
}
